import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_jpush/flutter_jpush.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sy_flutter_alipay/sy_flutter_alipay.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:zhrs/api/api.dart';
import 'package:zhrs/api/app_context.dart';
import 'package:zhrs/mainpage/mainindex.dart';
import 'package:zhrs/pages/face.dart';
import 'package:zhrs/pages/smart_service.dart';
import 'package:zhrs/service/audio_recorder.dart';
import 'package:zhrs/service/nfc_reader.dart';
import 'package:zhrs/utils/StaticContent.dart';
import 'package:zhrs/utils/alert_utils.dart' ;
import 'package:zhrs/utils/windowsSize.dart';

class Webviewpage extends StatefulWidget
{

  static bool finishpageload=false;
  static bool Isinformation=false;
  String url;
  Function reset;
  static String top;
  static bool istop=false;
  static bool finish=false;
  static WebViewController controller;
  Webviewpage({this.url="https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html",this.reset});

  @override
  Webviewpages createState()
  {

    return new Webviewpages();
  }
}

class Webviewpages extends State<Webviewpage>
{

  AudioRec audioRec;
   WebViewController controller;
  List<String> hashHex;
  int rangeIndex=0;
  //put 到hash列表
  void putHashHex(String val)  {
    rangeIndex=(rangeIndex==3?0:rangeIndex);
    hashHex[rangeIndex]=val;
    rangeIndex++;
   }
  //Onchange(int index,String url)  {
   // Navigator.push(context, MaterialPageRoute(builder:(context) =>Webviewpage(url:url ,Isinformation: true,)));
  //  Webviewpage.Isinformation=true;
  //  controller.loadUrl(url);
 // }
  @override
  void initState( ) {
    hashHex=['','',''];
    // TODO: implement initState
    super.initState();
  }
  @override
  Widget build(BuildContext context) {

    windowsSize.mapViewWidth = MediaQuery
        .of(context)
        .size
        .width;
    windowsSize.mapViewHeight = MediaQuery
        .of(context)
        .size
        .height;
    // TODO: implement build
    return   SafeArea(
        child: Scaffold (
          body:  new Container(
            child:  MediaQuery.removePadding (
              removeTop: true,
               context: context,
                 child: Container (
                  child: WillPopScope (
                     child:   WebView (
                                    //  key:item.key,
                                      initialUrl: widget.url,
                                      javascriptMode: JavascriptMode.unrestricted,
                                      onWebViewCreated: (WebViewController webViewController)
                                       {
                                          this.controller=webViewController;
                                          Webviewpage.controller=webViewController;
                                        },
                                      javascriptChannels: <JavascriptChannel>[
                                      _alertJavascriptChannel(context),
                                      _appJavascriptChannel(context),
                                      ].toSet(),
                                     navigationDelegate: (NavigationRequest request)  {
                                   if (request.url.startsWith('js://webview/queryUser')) {
                                  String userInfo =APP.userModel.loginname;
                                this.controller.evaluateJavascript(
                              'getUser("$userInfo")')
                          ?.then((result) {
                        print("result:$result");
                     });
                return NavigationDecision.prevent;
               }
             // if(Platform.isAndroid)  SystemChannels.textInput.invokeMethod('TextInput.hide');
              return NavigationDecision.navigate;
            },
            onPageFinished: (String url) async  {
              print('Page finished loading: $url');
              Webviewpage.finishpageload=true;
              ///当界面回退的时候执行
              if(Webviewpage.finish)
                {
                  if(!await controller.canGoBack())
                    {
                        Webviewpage.istop=false;
                        print("不能回头");
                        Webviewpage.finish=false;

                        if(MainindexState.hide[0]==!true)
                          {
                            widget.reset();
                          }
                    }
                  else
                    {
                      if(Webviewpage.istop)
                      {
                              controller.goBack();
                           // print("top"+Webviewpage.top);
                           // Webviewpage.istop=!Webviewpage.istop;
                           // controller.loadUrl(Webviewpage.top);
                      }
                    }
                }
            },
          ),
                       onWillPop: () async{
                       if(MainindexState.hide[0]==false)
                         {
                           Webviewpage.finish=true;
                           if(Webviewpage.Isinformation)
                           {
                             //this.controller.clearCache();
                             this.controller.goBack();
                             Webviewpage.Isinformation=false;
                             return false;
                             // widget.reset(url:"https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html");
                             // Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                             // Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                             // dispose();
                             // return Future.value(true);
                           }
                           else{
                             var canGoback= await this.controller?.canGoBack();
                             if(canGoback){

                               await controller?.goBack();
                               return Future.value(false);
                             }
                             // dispose();
                           }
                         }
                       else
                         {
                           Future<bool> canlogout= onWillPop(context);
                           canlogout.then((value){
                             if(value==true) dispose();
                           });
                           return canlogout;
                         }


                         //this.controller.clearCache();
                         //widget.reset();
                         //widget.reset(url:"https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html");
                        return false;
                       }),
     )
    )
    )
    )
    );
  }

  @override
  void dispose() {
    print("logout!!!!!!!!!!!");
    clearCache();

   if(audioRec!=null) audioRec.stop();
    super.dispose();
  }
  Future<void> clearCache() async{
   // bottomItems.forEach((item){
   //   item.webViewController.clearCache();
   // });
    this.controller.clearCache();
  }
  //音频录制
  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    if(audioRec==null) audioRec=AudioRec();
    return JavascriptChannel(
        name: 'Recorder',
        onMessageReceived: (JavascriptMessage message) {

          switch(message.message){
            case "start":
              audioRec.start(context).then((path){
                this.controller.evaluateJavascript(
                    'startRecordBackInfo("$path")')
                    ?.then((result) {
                  //print("result:$result");
                });
              });
              break;
            case "isRecording":
              audioRec.isRecording().then((isRecording){
                this.controller.evaluateJavascript(
                    'isRecordingBackInfo("$isRecording")')
                    ?.then((result) {
                  //print("result:$result");
                });
              });
              break;
            case "stop":
              audioRec.stop().then((path){
                print("path:$path");
                this.controller.evaluateJavascript(
                    'stopRecordBackInfo("$path")')
                    ?.then((result) {
                  //print("result:$result");
                });
              });
              break;
            default:
          }
        });
  }
  //app
  JavascriptChannel _appJavascriptChannel(BuildContext context)  {
    if(audioRec==null) audioRec=AudioRec();
    return JavascriptChannel (
        name: 'App',
        onMessageReceived: (JavascriptMessage message) async {
          List<String> mess=message.message.split(":");
          switch(mess[0]){
            case "logout":
              dispose();
              HttpManager.logout(context);
              break;
            case "callScanFace":
              showScanFace(context,mess[1]).then((action){
                this.controller.evaluateJavascript(
                    'callScanFaceBackInfo("$action")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "pickImage":
              int iq=60;
              if(mess[2]!=null) iq=int.parse(mess[2]);

              ImagePicker.pickImage(source: mess[1]=='1'?ImageSource.camera:ImageSource.gallery,imageQuality:iq).then((image){
                List<int> list= image.readAsBytesSync();

                String base64Str=base64.encode(list);
               this.controller.evaluateJavascript(
                    'pickImageBackInfo("$base64Str")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "pickImageToHash":
              int iq=60;
              if(mess[2]!=null) iq=int.parse(mess[2]);

              ImagePicker.pickImage(source: mess[1]=='1'?ImageSource.camera:ImageSource.gallery,imageQuality:iq).then((image){
                List<int> list= image.readAsBytesSync();
                //对文件进行hash
                var digest = sha256.convert(list);
                  // 这里其实就是 digest.toString()
                String hexStr= hex.encode(digest.bytes);
                hexStr=hexStr.toUpperCase();
                putHashHex(hexStr);

                this.controller.evaluateJavascript(
                    'hashImageBackInfo("$hexStr")')
                    ?.then((result) {
                  print("result:$result");
                });

                String base64Str=base64.encode(list);
               this.controller.evaluateJavascript(
                    'pickImageBackInfo("$base64Str")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "signSbk":
              String str='';
              try {
                hashHex.forEach((val){
                    if(val==''){
                      throw Exception("image$rangeIndex is null");
                    }
                    str=str+val;
                });
                var digest = sha256.convert(hex.decode(str));
                // 这里其实就是 digest.toString()
                String hexStr= hex.encode(digest.bytes);
                hexStr=hexStr.toUpperCase();
                NfcReader().instance.signSbk(hexStr).then((result){
                                this.controller.evaluateJavascript(
                                    'signSbkBackInfo("$result")')
                                    ?.then((result) {
                                  print("signSbk:$result");
                                });
                              });
              } catch (e) {
                print(e);
                this.controller.evaluateJavascript(
                    'signSbkBackInfo("${e.toString()}")');
              }
              break;
            case "callNFC":

              NfcReader().instance.readSbk().then((result){
                if(result!=null&&result.split(",").length==3){
                  String cardId= NfcReader().instance.resolving(result.split(",")[2]);
                  print("cardId:"+cardId);
                 this.controller.evaluateJavascript(
                      'callNFCBackInfo("$cardId")')
                      ?.then((result) {
                    print("result:$result");
                  });
                }
              });
              break;
            case "checkNFC":
              NfcReader().instance.checkNFC().then((result){
                this.controller.evaluateJavascript(
                    'checkNFCBackInfo("$result")')
                    ?.then((result) {
                  print("result:$result");
                });
              });
              break;
            case "openSmartService":

              Navigator.push(context, MaterialPageRoute(builder: (context)=>SmartService(mess[1]+':'+mess[2])));
              break;
            case "getCurrentPage":
             // var title=item_now.title;
             // this.controller.evaluateJavascript(
             //     'getCurrentPageBackInfo("$title")')
             //     ?.then((result) {
             //   print("result:$result");
             // });
              break;
            case "hideKeyBoard":
              try {
                if (Platform.isAndroid) SystemChannels.textInput.invokeMethod(
                    'TextInput.hide');
              }catch(e){
                print(e);
              }
              break;
            case "RegistrationID":
              try {

                String RegistrationID=StaticContent.RegistrationID;
                print(RegistrationID);
                if(RegistrationID==null)
                {

                  FlutterJPush.getRegistrationID().then((String regId) async{
                    StaticContent.RegistrationID=regId;
                  });
                }

                this.controller.evaluateJavascript(
                    'writeRegistrationID("$RegistrationID")')
                    ?.then((result) {
                  print("result:$result");
                });
              }catch(e){
                print(e);
              }
              break;
            case "Alipay":
              try{
                String payInfo=mess[1];
                print(payInfo);

               SyFlutterAlipay.pay(
                    payInfo,
                    urlScheme: '你的ios urlScheme', //前面配置的urlScheme
                    isSandbox: true //是否是沙箱环境，只对android有效
                ).then((res){
                  payInfo=res.toString();
                  print("结果："+ payInfo);
                  this.controller.evaluateJavascript(
                      'writeAlipay(\'$payInfo\')');
                });
              }
              catch(e){
                print(e);
              }
              break;
            case "Signature":
              try{

                alertSignature(context).then((val){

                  if(val!="null")
                  {
                    this.controller.evaluateJavascript(
                        'writeSignature(\'$val\')');
                  }

                });
              }
              catch(e){
                print(e);
              }
              break;
            case "Goback":
              try{
                Webviewpage.finish=true;
                if(Webviewpage.Isinformation)
                {
                     //controller.clearCache();
                     Webviewpage.Isinformation=false;
                 //widget.reset(url:"https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html");
                 // Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                 //Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                 //dispose();
                }
                else{

                  if(mess.length>=2)
                  {
                     if(mess[1]=="top")
                       {
                         widget.reset();
                         Webviewpage.istop=true;
                         print("调用了");
                            controller.goBack( );
                        // print("top:"+Webviewpage.top);
                        // await controller.loadUrl(Webviewpage.top);
                        //widget.reset(url:"https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html");
                        /* if(Navigator.pop(context))
                         {

                         }
                         else
                         {
                           Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                         }
                         dispose();
                         */

                       }
                  }
                    else
                      {

                        var canGoback= await this.controller.canGoBack();
                        if(canGoback){
                          await controller.goBack();
                        }
                     /*   this.controller?.canGoBack().then((canGoback)
                        {
                          if(canGoback){
                            controller?.goBack();
                          }
                          else
                          {
                            //this.controller.loadUrl("https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html");
                            // widget.reset(url:"https://www.dzsbk.cn/smartDemo/page/clearlocalstorage.html");
                            /*  if(Navigator.pop(context))
                        {
                        }
                        else
                        {
                          Navigator.push(context, MaterialPageRoute(builder:(context) =>Mainindex(index:int.parse(APP.userModel.userId,)  )));
                        }
                        dispose();
                        */
                          }
                        });
                        */
                      }

                }
              }
              catch(e)
              {
                print(e);
              }
              break;

            default:

          }
        });
  }
}
Future<String> showScanFace(BuildContext context,String title) async{
  var action = await showDialog(context: context,builder: (context){
    return Scaffold(
      body: Container(
        width: 400.0,
        height: 600.0,
        child:FaceScan(title: title,),
      ),
    );
  });
  return action;
}
